package com.project.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.bean.BuyBean;
import com.project.bean.BuyCarBean;
import com.project.bean.BuyInfoBean;
import com.project.bean.ProductBean;
import com.project.mapper.IBuyMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Collection;
import java.util.Map;

@Service
@Transactional
public class BuyServiceImpl implements IBuyService {
    @Autowired
    private IBuyMapper mapper;
    @Autowired
    private IProductMapper productMapper;
    @Override
    public  Map<Integer, BuyCarBean> add(String method, ProductBean product, Map<Integer, BuyCarBean> shopMap, int number) {
        BuyCarBean buyCar = new BuyCarBean();
        buyCar.setNum(number);
        buyCar.setProduct(product);
            if(method.equals("add")){
                productMapper.add(product);
                shopMap.put(product.getId(),buyCar);
            }else {
                shopMap.put(product.getId(),buyCar);
            }
            return shopMap;
    }

    @Override
    public void del(Map<Integer, BuyCarBean> shopMap, int productId) {
            shopMap.remove(productId);
    }

    @Override
    public void sureBuy(Map<Integer, BuyCarBean> shopMap, BuyBean buy) {
        mapper.addBuy(buy);
        Collection<BuyCarBean> buyCarCollection = shopMap.values();
        for(BuyCarBean b : buyCarCollection){
            productMapper.updateStoreNum(b.getProduct().getId(),b.getNum());
            mapper.addBuyInfo(new BuyInfoBean(buy.getId(), b.getProduct().getId(), b.getNum()));
        }
        shopMap.clear();
    }

    @Override
    public PageInfo<BuyBean> cutByItem(int pageNO, String supName, LocalDate startDate, LocalDate endDate) {
        PageHelper.startPage(pageNO, PAGESIZE);
        PageInfo pageInfo =  PageInfo.of(mapper.cutByItem(supName, startDate, endDate));

        return pageInfo;
    }

    @Override
    public BuyBean findById(int id) {
        System.out.println(mapper.findById(id));
        return mapper.findById(id);
    }

    @Override
    public void updateNum(int productId, int number,Map<Integer, BuyCarBean> shopMap) {
        BuyCarBean buyCarBean =  shopMap.get(productId);
        buyCarBean.setNum(number);
    }
}
